$(function () {

    let getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    let userId = getUrlParam('user')
    let touser = "";
    let currentTab = "好友列表";
    let roomid = ""

    const socket = io('/', {
        // 实际使用中可以在这里传递参数
        query: {
            room: "chat",
            userId: userId,
        },
        transports: ['websocket']
    });

    window.socket = socket;

    /**连接工作室后 加载在线列表 */
    socket.on('connect', () => {
        socket.emit("online", "")
    })

    /**显示在线列表函数 */
    let showOnlineList = function (data) {
        let liStr = ``
        for (let d of data) {
            if (d.account == userId) continue
            liStr += `<a href="#" class="list-group-item"> <span class="userName">${d.account}</span><span class="badge">在线</span></a></li>`
        }
        $("#onlinelist").html(liStr)
        liStr = ``
        for (let d of data) {
            if (d.account == userId) continue
            liStr += `<div class="checkbox form-control">
                    <label><input type="checkbox" name="friendList" value="">${d.account}</label>
                </div>`

        }
        $("#friendlist").html(liStr)
    }

    /**显示数据函数 */
    let showMsg = function (datas) {
        let liStr = ``;
        //console.log(datas);

        for (let i = 0, len = datas.length; i < len; i++) {
            let d = datas[i]
            let date = (new Date(d.create_time)).toLocaleString()
            let c = ""
            if (userId == d.user) c = "text-right"
            if (d.img != undefined && d.img != "") {
                liStr += `<li><p class="text-center">${date}</p><p class=${c}>${d.user}</p><p class=${c}><span style="background-color:#dcecb5"><img src="${d.img}"/></span></p></li>`
            } else {
                liStr += `<li><p class="text-center">${date}</p><p class=${c}>${d.user}</p><p class=${c}><span style="background-color:#dcecb5"> ${d.message}</span> </p></li>`
            }
        }
        $("#messages").html(liStr)
    }

    /**发送信息的函数 */
    let sendMsg = function (d) {

        let data = {}
        let url = ""
        if (currentTab == "好友列表") {
            data = Object.assign({
                user: userId,
                touser: touser
            }, d)
            url = "/api/v1/chat"
        } else if (currentTab == "群聊") {
            data = Object.assign({
                user: userId,
                room: roomid
            }, d)
            url = "/api/v1/roommsg"
        }

        $.ajax({
            url: url,
            method: "post",
            data: data
        }).then(function (data) {
            let datas = data.data
            if (!datas instanceof Array) datas = new Array(datas)
            $("#msg").val("")
            //showMsg(datas)
            if (currentTab == "好友列表") {
                socket.emit('chat', { user: userId, touser: touser })
            } else {
                socket.emit('chatroommsg', { roomid: roomid })
            }
        })
    }


    /**在线列表 */
    socket.on('online', function (data) {
        showOnlineList(data)
    })

    /**当前聊天数据 */
    $("#onlinelist").on("click", "a", function () {
        $('#onlinelist .active').removeClass('active')
        $(this).addClass('active')
        touser = $(this).find(".userName").text()
        $(this).find(".badge").text("在线")
        socket.emit("chat", { user: userId, touser: touser })

    })


    /**接受消息 */
    socket.on('message', function (data) {
        if (currentTab == "好友列表") {
            if ((userId == data.fromuser && touser == data.touser) || (touser == data.fromuser && userId == data.touser)) {
                showMsg(data.data)
            }
        } else if (currentTab = "群聊") {
            if (data.tousers.includes(userId) && roomid == data.roomid) {
                showMsg(data.data)
            }
        }
    })

    /**消息提醒 */
    socket.on('remindNew', function (data) {
        if (currentTab == "好友列表") {
            let lis = $("#onlinelist a")
            for (let i = 0, len = lis.length; i < len; i++) {
                if (lis.eq(i).find('.userName').text() == data.fromuser) {
                    if (lis.eq(i).is('.active')) break
                    lis.eq(i).find('.badge').text('新消息')
                }
            }
        } else {
            let lis = $("#chatslist a")
            for (let i = 0, len = lis.length; i < len; i++) {
                
                if (lis.eq(i).attr("id") == data.roomid) {
                    
                    if (lis.eq(i).is('.active')) break
                    lis.eq(i).find('.badge').text('新消息')
                }
            }
        }
    })

    /**上传图片 */
    $('#file').change(function () {
        console.log('1');
        console.log($(this).val());
        var form = new FormData();
        form.append('img', $('#file')[0].files[0]);
        $.ajax({
            type: "post",
            url: "/api/v1/upload",
            data: form,
            processData: false,
            contentType: false
        }).then(function (response) {
            $('#tishi').text('选择成功')
            sendMsg({ img: response.url })
        }, function (response) {
            alert("错误！！");
        })
    })

    /**回车发送消息 */
    $('#msg').on('keyPress', function (e) {
        console.log(e.keyCode);
    })

    /**发送消息 */
    $("#send").click(function () {
        let d = {}
        if (currentTab == "好友列表") {
            d = {
                user: userId,
                touser: touser
            }
        } else if (currentTab == "群聊") {
            d = {
                //user: userId,
                roomid: roomid
            }
        }
        if (((touser != "" && currentTab == "好友列表")||currentTab == "群聊") && $("#msg").val() != "") {
            sendMsg({ message: $("#msg").val() })
            socket.emit("remindNew", d)
        }
    })

    /**退出聊天室 */
    $("#logout").click(function () {
        socket.emit("logout", { userName: userId })
        document.location.href = "/login.html"
    })

    socket.on('connect_error', err => {
        socket.disconnect()
        console.log('connect_error', err)
    })


    /**
     * 
     * 
     *  群聊
     * 
     */
    /**切换群聊 */

    //切换好友列表与群聊
    $("#pills").on("click", "li", function () {
        $('#pills .active').removeClass('active')
        $(this).addClass('active')
        //console.log($(this).text());

        if ($(this).text() == "群聊") {
            $("#onlinelist").addClass('hide')
            $("#chats").removeClass('hide')
            currentTab = "群聊"
            touser = ""
            socket.emit('chatRoomList', { user: userId })
        } else if ($(this).text() == "好友列表") {
            $("#onlinelist").removeClass('hide')
            $("#chats").addClass('hide')
            currentTab = "好友列表"
            rommid = ""
        }
    })

    //创建群聊
    $('#comfirmFriendCheck').click(function () {
        let labels = $("#friendlist label");
        let chatPersions = [userId];
        let chatroom = $('#chatroom').val()
        for (let i = 0, len = labels.length; i < len; i++) {
            //console.log($(labels[i]).find('input').is(':checked'));
            if ($(labels[i]).find('input').is(':checked')) {
                chatPersions.push($(labels).eq(i).text())
            }
        }
        $.ajax({
            type: "post",
            url: "/api/v1/room",
            data: {
                user: userId,
                tousers: chatPersions,
                name: chatroom
            }
        }).then(function (res) {
            console.log(res);
            $("#chatslist").append(`<a href="#" class="list-group-item"  id="${res.data._id}>
             <span class="userName">${res.data.name}</span><span class="badge"></span></a>`)

        }, function (res) {

        })
    })

    //聊天群列表点击
    $("#chatslist").on("click", "a", function () {
        $('#chatslist .active').removeClass('active')
        $(this).addClass('active')
        $(this).find('.badge').text()
        roomid = $(this).attr('id')
        socket.emit("chatroommsg", { user: userId, roomid: roomid })
    })

    //加载聊天群列表
    socket.on('chatRoomList', function (data) {
        let liStr = ``
        //console.log(data);

        for (let d of data) {
            if (d.account == userId) continue
            liStr += `<a href="#" class="list-group-item" id="${d._id}"> <span class="userName" >${d.name}</span><span class="badge"></span></a></li>`
        }
        $("#chatslist").html(liStr)
    })

})

